﻿using System;
using System.Drawing.Design;
using System.Windows.Forms;
using System.Windows.Forms.Design;
using ApplicationGenerator.Forms.WebControls;

namespace ApplicationGenerator.Forms.Forms
{
    public class ModelHierarchyEditor : UITypeEditor
    {

        public override UITypeEditorEditStyle GetEditStyle(System.ComponentModel.ITypeDescriptorContext context)
        {
            return UITypeEditorEditStyle.Modal;
        }

        public override object EditValue(System.ComponentModel.ITypeDescriptorContext context, IServiceProvider provider, object value)
        {
            if (context != null)
            {
                if (context.Instance != null)
                {
                    BaseMappedControl mappedControl = context.Instance as BaseMappedControl;
                    if (mappedControl == null)
                    {
                        throw new Exception("Klasa która używa edytora ModelHierarchyEditor musi dziedziczyć z klasy BaseMappedControl.");
                    }

                    IWindowsFormsEditorService editorService = null;

                    if (provider != null)
                    {
                        editorService =
                            provider.GetService(
                            typeof(IWindowsFormsEditorService))
                            as IWindowsFormsEditorService;
                    }
                    if (editorService != null)
                    {
                        SelectModelFieldForm formModel = new SelectModelFieldForm(mappedControl);
                        if (editorService.ShowDialog(formModel) == DialogResult.OK)
                        {
                            value = formModel.Path;
                        }
                    }
                }
            }
            return value;
        }
    }
}
